package com.example.loginlib

import android.os.Bundle
import android.os.CountDownTimer
import android.os.SystemClock
import android.text.Editable
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.Base64
import android.view.View
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.lifecycle.Observer

import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.baselib.activity.BaseViewModelActivity
import com.example.baselib.constants.ARConstants
import com.example.baselib.constants.MyConstants
import com.example.baselib.dialog.MsgDialog
import com.example.baselib.utils.EquipmentUtil
import com.example.baselib.utils.PermissionsUtils
import com.google.gson.Gson
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.activity_login.*

// 在支持路由的页面上添加注解(必选)
// 这里的路径需要注意的是至少需要有两级，/xx/xx
@Route(path = ARConstants.APP_Login)
class LoginActivity : BaseViewModelActivity<LoginViewModel>(), View.OnFocusChangeListener {
    private var showP = false
    private lateinit var mmkv: MMKV
    private var mCountDownTimer: CountDownTimer? =null

    override fun onCreate(savedInstanceState: Bundle?) {
        MMKV.initialize(this.applicationContext)
        mmkv = MMKV.defaultMMKV()
        super.onCreate(savedInstanceState)
    }
    override fun providerVMClass(): Class<LoginViewModel>? = LoginViewModel::class.java

    override fun layoutResId(): Int {
        return R.layout.activity_login
    }

    override fun initView() {
        setShowToolbar(false)
        login_edit_username.onFocusChangeListener = this
        login_edit_pwd.onFocusChangeListener = this
        login_edit_tel.onFocusChangeListener = this
        login_edit_vef.onFocusChangeListener = this
        login_edit_username.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                btnEnabled()
                login_clear_username?.visibility =
                    if (s?.length!! > 0) View.VISIBLE else View.INVISIBLE
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        login_edit_pwd.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                btnEnabled()
                login_pwd_sh?.visibility = if (s?.length!! > 0) View.VISIBLE else View.INVISIBLE
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        login_edit_tel.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                btnEnabled()
                login_clear_tel?.visibility = if (s?.length!! > 0) View.VISIBLE else View.INVISIBLE
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
        login_edit_vef.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                btnEnabled()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })
        login_clear_username.setOnClickListener {
            login_edit_username.text.clear()
            login_edit_username.requestFocus()
        }
        login_clear_tel.setOnClickListener {
            login_edit_tel.text.clear()
            login_edit_tel.requestFocus()
        }
        login_pwd_sh.setOnClickListener {
            if (!showP) {// 显示密码
                login_pwd_sh?.background =
                    login_pwd_sh?.let { getDrawable(R.mipmap.login_pwd_show) }
                login_edit_pwd.transformationMethod = HideReturnsTransformationMethod.getInstance()
                login_edit_pwd.setSelection(login_edit_pwd.text.length)
                showP = !showP
            } else {// 隐藏密码
                login_pwd_sh?.background =
                    login_pwd_sh?.let { getDrawable(R.mipmap.login_pwd_hide) }
                login_edit_pwd.transformationMethod = PasswordTransformationMethod.getInstance()
                login_edit_pwd.setSelection(login_edit_pwd.text.length)
                showP = !showP
            }
            login_edit_pwd.requestFocus()
        }
        login_choose_type.setOnClickListener {
            if (login_pwd_cly.visibility == View.VISIBLE) {
                login_pwd_cly.visibility = View.INVISIBLE
                login_tel_cly.visibility = View.VISIBLE
                login_choose_type.text = "切换手机号/用户名登录"
            } else {
                login_pwd_cly.visibility = View.VISIBLE
                login_tel_cly.visibility = View.INVISIBLE
                login_choose_type.text = "切换短信验证码登录"
            }
            btnEnabled()
        }
        login_btn.setOnClickListener {
            if(!isFastClick()){
                if (login_pwd_cly.visibility == View.VISIBLE) getPermission() else telLogin()
            }
        }
        login_send_vef.setOnClickListener { sendVef() }
        setUrl()
    }

    private fun setUrl() {
        val counts = 5
        val duration: Long = 2 * 1000
        var mHits = LongArray(counts)
        login_img_log.setOnClickListener {
            System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
            //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
            mHits[mHits.size - 1] = SystemClock.uptimeMillis()
            if (mHits[0] >= (SystemClock.uptimeMillis() - duration)) {
                //                val tips = "您已在[" + duration + "]ms内连续点击【" + mHits.size + "】次了！！！"
                //                Toast.makeText(applicationContext,tips,Toast.LENGTH_SHORT)?.show()
                ChooseUrlDialog().show(supportFragmentManager, "ChooseUrlDialog")
                mHits = LongArray(counts)
            }
        }
    }

    override fun initData() {
        login_edit_username.setText(mmkv.decodeString("username"))
        login_edit_pwd.setText(mmkv.decodeString("password"))
        login_edit_tel.setText(mmkv.decodeString("tel"))
        initNameUi()
        initPwdUi()
        initTelUi()
        initVefUi()
        viewModel.getLoginDatas().observe(this, Observer {
            MyConstants.userData = it
            mmkv.encode("username", login_edit_username.text.toString())
            mmkv.encode("password", login_edit_pwd.text.toString())
            ARouter.getInstance().build(ARConstants.APP_MAIN)
                .navigation()
            finish()
        })

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (PermissionsUtils.requestPermissionResult(this, permissions, grantResults)) {
            0 -> if (requestCode == 777) {
                pwdLogin()
            }
            -2 -> MsgDialog("请前往应用设置界面手动开启权限").show(
                supportFragmentManager,
                "requestPermissionResult"
            )
            else -> return
        }
    }


    override fun onFocusChange(v: View?, hasFocus: Boolean) {
        if (hasFocus) {
            when (v) {
                login_edit_username -> {
                    changeShowUi(login_user_img, R.mipmap.login_user_2, null, login_user_line)
                }
                login_edit_pwd -> {
                    changeShowUi(login_pwd_img, R.mipmap.login_lock_2, null, login_pwd_line)
                }
                login_edit_tel -> {
                    changeShowUi(login_tel_img, R.mipmap.login_tel_2, null, login_tel_line)
                }
                login_edit_vef -> {
                    changeShowUi(login_vef_img, R.mipmap.login_vercode_2, null, login_vef_line)
                }
            }
        } else {
            when (v) {
                login_edit_username -> {
                    initNameUi()
                }
                login_edit_pwd -> {
                    initPwdUi()
                }
                login_edit_tel -> {
                    initTelUi()
                }
                login_edit_vef -> {
                    initVefUi()
                }
            }
        }
    }


    /**
     *初始化edittext 的img
     */
    private fun initVefUi() {
        if (!login_edit_vef.text.isNullOrEmpty()) {
            changeShowUi(login_vef_img, R.mipmap.login_vercode_2, null, login_vef_line)
        } else {
            changeHideUi(login_vef_img, R.mipmap.login_vercode_1, null, login_vef_line)
        }
    }

    /**
     *初始化edittext 的img
     */
    private fun initTelUi() {
        if (!login_edit_tel.text.isNullOrEmpty()) {
            changeShowUi(
                login_tel_img,
                R.mipmap.login_tel_2,
                login_clear_tel,
                login_tel_line
            )
        } else {
            changeHideUi(
                login_tel_img,
                R.mipmap.login_tel_1,
                login_clear_tel,
                login_tel_line
            )
        }
    }

    /**
     *初始化edittext 的img
     */
    private fun initPwdUi() {
        if (!login_edit_pwd.text.isNullOrEmpty()) {
            changeShowUi(
                login_pwd_img,
                R.mipmap.login_lock_2,
                login_pwd_sh,
                login_pwd_line
            )
        } else {
            changeHideUi(
                login_pwd_img,
                R.mipmap.login_lock_1,
                login_pwd_sh,
                login_pwd_line
            )
        }
    }

    /**
     *初始化edittext 的img
     */
    private fun initNameUi() {
        if (!login_edit_username.text.isNullOrEmpty()) {
            changeShowUi(
                login_user_img,
                R.mipmap.login_user_2,
                login_clear_username,
                login_user_line
            )
        } else {
            changeHideUi(
                login_user_img,
                R.mipmap.login_user_1,
                login_clear_username,
                login_user_line
            )
        }
    }

    /**
     *edittext 有内容
     */
    private fun changeShowUi(leftview: View?, leftimg: Int?, rightview: View?, lineview: View?) {
        leftview?.background = leftimg?.let { getDrawable(it) }
        rightview?.visibility = View.VISIBLE
        lineview?.background = getDrawable(R.color.colorWhite)
    }

    /**
     *edittext 无内容
     */
    private fun changeHideUi(leftview: View?, leftimg: Int?, rightview: View?, lineview: View?) {
        leftview?.background = leftimg?.let { getDrawable(it) }
        rightview?.visibility = View.INVISIBLE
        lineview?.background = getDrawable(R.color.colorBlue30)
    }

    /**
     *控制button
     */
    private fun btnEnabled() {
        login_btn.isEnabled =
            if (login_pwd_cly.isVisible) !login_edit_username.text.isNullOrEmpty() && !login_edit_pwd.text.isNullOrEmpty()
            else (!login_edit_tel.text.isNullOrEmpty() && !login_edit_vef.text.isNullOrEmpty())
    }

    /**
     * @Description: [密码登录前或取权限]
     * @Param:
     * @Return:
     */
    private fun getPermission() {
        if (PermissionsUtils.isRequestPermission()) {
            if (PermissionsUtils.startRequestPermission(
                    this,
                    PermissionsUtils.PHONE_STATE_PERMISSIONS,
                    777
                )
            ) {
                pwdLogin()
            }
        } else {
            pwdLogin()
        }
    }

    /**
     * @Description: [密码登录]
     * @Param:
     * @Return:
     */
    private fun pwdLogin() {
        val simInfo = EquipmentUtil.getDeviceInfo(this)
        val textByte = Gson().toJson(simInfo).toByteArray(charset("UTF-8"))
        val unique = Base64.encodeToString(textByte, Base64.DEFAULT)
//        val unique=""
//        loadingDialog.show(supportFragmentManager, "getPermission")
        viewModel.loginByPwd(
            unique,
            login_edit_username.text.toString(),
            login_edit_pwd.text.toString()
        )
    }

    /**
     * @Description: [发送验证码]
     * @Param:
     * @Return:
     */
    private fun sendVef() {
        if (login_edit_tel.text.isNullOrEmpty()) {
            Toast.makeText(this, "请填写手机号", Toast.LENGTH_SHORT).show()
        } else {
            countDown()
            login_send_vef.isEnabled = false
            viewModel.getVerificationCode(login_edit_tel.text.toString())
        }
    }

    /**
     * 60秒倒计时
     */
    private fun countDown(){
        var count = 0
        mCountDownTimer= object : CountDownTimer((60 * 1000).toLong(), (1 * 1000).toLong()) {
            override fun onTick(millisUntilFinished: Long) {

                login_send_vef.text = ((60 - count).toString()) + "s"
                count++
            }

            override fun onFinish() {
                mCountDownTimer?.cancel()
                count = 1
                login_send_vef.isEnabled = true
                login_send_vef.text = "获取验证码"
            }
        }
        mCountDownTimer?.start()

    }

    /**
     * @Description: [验证码登录]
     * @Param:
     * @Return:
     */
    private fun telLogin() {
//        loadingDialog.show(supportFragmentManager, "getPermission")
        viewModel.loginByTel(login_edit_tel.text.toString(),login_edit_vef.text.toString())

    }

    override fun onDestroy() {
        mCountDownTimer?.cancel()
        super.onDestroy()

    }
}
